<template>
  <div class="edit-photo-container">
     <div class="img-container">
        <img :src="imgSrc" ref="image" alt="">
      </div>
    <van-nav-bar
  right-text="确认"
  left-text="取消"
  @click-right="sureSava"
  @click-left="$emit('update:isShowEditPhoto', false)"
/>
  </div>
</template>

<script>
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { updateUserPhoto } from 'network/user'
export default {
  name: 'EditPhoto',
  props: {
    imgSrc: {
      type: String
    },
    isShowEditPhoto: {
      type: Boolean
    },
    userInfo: {
      type: Object
    }
  },
  data () {
    return {
      myCropper: null,
      afterImg: ''
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    init () {
      this.myCropper = new Cropper(this.$refs.image, {
        viewMode: 1,
        dragMode: 'move',
        initialAspectRatio: 1,
        aspectRatio: 1,
        preview: '.before',
        background: false,
        autoCropArea: 0.6,
        zoomOnWheel: false
      })
    },
    getcroppedCanvas () {
      return new Promise(resolve => {
        this.myCropper.getCroppedCanvas().toBlob(blob => {
          resolve(blob)
        })
      })
    },
    async sureSava () {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        loadingType: 'spinner',
        message: '保存中'
      })
      try {
        const formData = new FormData()
        const file = await this.getcroppedCanvas()
        console.log(file)
        // formData.append('名字', 数据)
        formData.append('photo', file)
        const { data: res } = await updateUserPhoto(formData)
        this.$emit('update:isShowEditPhoto', false)
        this.userInfo.photo = res.data.photo
        console.log(res)
        this.$toast.success('保存成功')
      } catch (err) {
        console.log(err)
        this.$toast.fail('保存失败')
      }
    }
  }
}
</script>

<style lang='less' scoped>
.edit-photo-container{
    background-color: black;
    .van-nav-bar{
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
    }
    .img-container{
        height: 500px;
    }
}
</style>
